var express = require('express');
var router = express.Router();
var request = require('request');

var CommonJS = require('../../../common/common');
var DBConfig = require('../../../db/dbconfig');
var mysql = require('mysql');
var pool = mysql.createPool(DBConfig.mysql2);

var Wx_config = require('../../../wx_config/wx_config');
var WXBizDataCrypt = require('../../../wx_config/WXBizDataCrypt');

// 微信登录 获取用户openid
// oJDAU0fMTDBEQ_oRyNcuiHlq5t5I
router.get('/jkyx/wx_login', function(req, res, next) {
	var param = req.query || req.params; 
	var code = param.code;
	var encryptedData = param.encryptedData;
	var iv = param.iv;
	var wxUrl = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + Wx_config.AppID + '&secret=' + Wx_config.Secret + '&js_code=' + code + '&grant_type=authorization_code';
	request(wxUrl, function (error, response, body) {
		if (!error && response.statusCode == 200) {
			var body = JSON.parse(body);
			var sessionKey = body.session_key;
			pool.getConnection(function(err, connection) {
				if(err){
					res.end(JSON.stringify({
		     			msg: '数据库连接失败',
		     			status:'101',
		     		}));
				}
				connection.query(DBConfig.getOpendiByOpenid,[body.openid],function (err, results) {
					connection.release();
					if (err){
					  	res.end(JSON.stringify({
			     			msg: '数据库查询失败',
			     			status:'102',
			     			err: err
			     		}));
					}else{
						var status = '100';
						if (results.length == 0) {
							res.end(JSON.stringify({
				     			msg: '操作失败',
				     			status: '101',
				     			data: body
				     		}));	
						}else{
							var pc = new WXBizDataCrypt(Wx_config.AppID, sessionKey);
							var data = pc.decryptData(encryptedData , iv)
							res.end(JSON.stringify({
				     			msg: '操作成功',
				     			status: '100',
				     			data: body,
				     			data2: data,
				     			userInfo: results[0]
				     		}));	  	
						}       
					}
				})
			})   
		}else{
			res.end(JSON.stringify({
				msg: '获取失败',
				status:'101',
			}));	 
		}
	})
});





// 登录请求
router.get('/jkyx/login', function(req, res, next) {
	var param = req.query || req.params; 
//	console.log(param);
	// 手机号
	var tel = param.tel || '';
	// 验证码
	var varcode = param.varcode || '';
	// 用户微信openid
	var openid = param.openid || '';
	// 微信昵称
	var wx_nickname = param.wx_nickname || '';
	// 用户微信头像
	var avatarUrl = param.avatarUrl || '';
	// 用户微信性别
	var gender = param.gender || 1;
	// 获取客户端ip
	var ip = req.ip.replace(/::ffff:/, ''); 
	ip = '113.57.89.30';
    pool.getConnection(function(err, connection) {
		if(err){
			res.end(JSON.stringify({
     			msg: '数据库连接失败',
     			status:'101',
     		}));
		}else{
			connection.query(DBConfig.login_check,[tel,tel],function (err, results) {
				if (err){
					connection.release();
				  	res.end(JSON.stringify({
		     			msg: '数据库查询失败',
		     			status:'102',
		     			err: err
		     		}));
				}else{
					// 用户信息
					var userInfo = results[0];
					if (results[1].length == 0) {
						res.end(JSON.stringify({
			     			msg: '验证码无效',
			     			status:'107'
			     		}));
			     		return;
					}
					// 验证码
					var sendTimer = results[1][0].create_time;
					var sendCode = results[1][0].identify_code;
					// 用户之前没账号
					if (userInfo.length == 0) {
//						console.log('用户不存在');
						var timer = CommonJS.timestamp();
						var is_time_out = timer - sendTimer; 
						if (is_time_out > CommonJS.time_out) { // 验证码过期 超过 5分钟
							varCode_isOver(tel,connection,res);
						} else{
							insertUser(ip,tel,connection,res,wx_nickname,avatarUrl,openid,gender);
						}
					}else{ // 用户存在
//						console.log('用户存在');
						loginUser(ip,tel,connection,res,wx_nickname,avatarUrl,openid,gender)
					}
				}
			})
		}
	})					
});

// 验证码过期了
function varCode_isOver(tel,connection,res){
	connection.query(DBConfig.varCode_isOver,[tel],function (err, results) {
		connection.release();
		if (err){
		  	res.end(JSON.stringify({
     			msg: '数据库查询失败',
     			status:'105',
     			err: err
     		}));
		}else{
			res.end(JSON.stringify({
     			msg: '验证码已过期',
     			status:'106',
     		}));
		}
	})
}
// 新增用户
function insertUser(ip,tel,connection,res,wx_nickname,avatarUrl,openid,gender){
	var taobaoIP = 'http://ip.taobao.com/service/getIpInfo.php?ip=' + ip;
	// 获取用户地址
	request(taobaoIP, function (error, response, body) {
		var provice = '';
		var city = '';
		var area = '';
		if (!error && response.statusCode == 200) {
			body = JSON.parse(body);
			provice = body.data.region || '';
			city = body.data.city || '';
			area = body.data.isp || '';
		}
		var create_time = CommonJS.getNowFormatDate();
		var sql = 'insert into account (account_id,account,wx_nickname,avatarUrl,openid,gender,create_time) values (?,?,?,?,?,?,?);' + DBConfig.loginWithAccount;
		connection.query(sql,[
			tel,
			tel,
			wx_nickname,
			avatarUrl,
			openid,
			gender,
			create_time,		
			tel,
			tel,
			1,
			ip,
			provice,
			city,
			area,
			create_time,
			tel
		],function (err, results) {
			connection.release();
			if (err){
			  	res.end(JSON.stringify({
	     			msg: '数据库查询失败',
	     			status:'102',
	     			err: err
	     		}));
			}else{
				res.end(JSON.stringify({
	     			msg: '登录成功',
	     			status:'100',
	     			userInfo: results[3][0]
	     		}));
			}
		})
	})
}
// 登录
function loginUser(ip,tel,connection,res,wx_nickname,avatarUrl,openid,gender){
	var taobaoIP = 'http://ip.taobao.com/service/getIpInfo.php?ip=' + ip;
	// 获取用户地址
	request(taobaoIP, function (error, response, body) {
		var provice = '';
		var city = '';
		var area = '';
		if (!error && response.statusCode == 200) {
			body = JSON.parse(body);
			provice = body.data.region || '';
			city = body.data.city || '';
			area = body.data.isp || '';
		}
		var create_time = CommonJS.getNowFormatDate();
		var sql = 'update account set wx_nickname = ?,avatarUrl = ?,openid = ?,gender = ? where account = ?;' + DBConfig.loginWithAccount;
		connection.query(sql,[
			wx_nickname,
			avatarUrl,
			openid,
			gender,
			tel,		
			tel,
			tel,
			1,
			ip,
			provice,
			city,
			area,
			create_time,
			tel
		],function (err, results) {
			connection.release();
			if (err){
			  	res.end(JSON.stringify({
	     			msg: '数据库查询失败',
	     			status:'102',
	     			err: err
	     		}));
			}else{
				res.end(JSON.stringify({
	     			msg: '登录成功',
	     			status:'100',
	     			userInfo: results[3][0]
	     		}));
			}
		})
	})
}


// 退出登录
router.get('/jkyx/login_out', function(req, res, next) {
	var param = req.query || req.params; 
	// 手机号
	var tel = param.tel || '';
	// 验证码
	var varcode = param.varcode || '';
	// 获取客户端ip
	var ip = req.ip.replace(/::ffff:/, ''); 
	ip = '113.57.89.30';
    pool.getConnection(function(err, connection) {
		if(err){
			res.end(JSON.stringify({
     			msg: '数据库连接失败',
     			status:'101',
     		}));
		}else{
			var taobaoIP = 'http://ip.taobao.com/service/getIpInfo.php?ip=' + ip;
			request(taobaoIP, function (error, response, body) {
				var provice = '';
				var city = '';
				var area = '';
	   			if (!error && response.statusCode == 200) {
	   				body = JSON.parse(body);
	   				provice = body.data.region || '';
	   				city = body.data.city || '';
	   				area = body.data.isp || '';
	   			}
	   			connection.query(DBConfig.loginOutWithAccount,[tel,2,ip,provice,city,area,CommonJS.getNowFormatDate()],function (err, results) {
					connection.release();
					if (err){
					  	res.end(JSON.stringify({
			     			msg: '数据库查询失败',
			     			status:'102',
			     			err: err
			     		}));
					}else{
						res.end(JSON.stringify({
		         			msg: '登出成功',
		         			status:'100',
		         		}));
					}
				})
	   		})
		}
	})
});

module.exports = router;
